package com.haoma.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoma.constant.RedisConstant;
import com.haoma.dto.AdminDto;
import com.haoma.entity.Admin;
import com.haoma.exception.BlogException;
import com.haoma.mapper.AdminMapper;
import com.haoma.minio.MinIOConfig;
import com.haoma.minio.MinIOConfigProperties;
import com.haoma.result.Result;
import com.haoma.service.AdminService;
import com.haoma.utils.JwtHelper;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Description: 管理员用户相关业务
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 登录
    public Result login(Admin admin) {
        // 查询数据库
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getPassword, admin.getPassword());
        adminLambdaQueryWrapper.eq(Admin::getUsername, admin.getUsername());
        Admin adminDb = adminMapper.selectOne(adminLambdaQueryWrapper);
        if (adminDb == null) {
            // 抛出错误信息
            throw new BlogException("用户名或密码错误");
        }
        // 正确生成token
        String token = JwtHelper.createToken(Long.valueOf(adminDb.getId()));
        // 存储到redis中
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + adminDb.getId(), token, RedisConstant.USER_LOGIN_TIME, TimeUnit.MINUTES);
        // 创建一个返回对象
        adminDb.setToken(token);
        System.out.println(adminDb);
        return Result.success(adminDb);
    }

    @Override
    public Result logout() {
        // 从redis中删除
        stringRedisTemplate.delete(RedisConstant.USER_LOGIN_KEY_PREFIX + 1);
        return Result.success();
    }

    /**
     * 修改信息接口
     *
     * @param adminDto
     * @return
     */
    public Result reset(AdminDto adminDto) {
        // 查询数据库
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getPassword, adminDto.getPassword());
        adminLambdaQueryWrapper.eq(Admin::getUsername, adminDto.getUsername());
        Admin adminDb = adminMapper.selectOne(adminLambdaQueryWrapper);
        if (adminDb == null) {
            // 抛出错误信息
            throw new BlogException("用户名或密码错误");
        }
        if (StringUtils.hasText(adminDto.getRepassword())) {
            // 重置密码
            adminDb.setPassword(adminDto.getRepassword());
        }
        if (StringUtils.hasText(adminDto.getPhotoUrl())) {
            // 修改头像
            adminDb.setPhotoUrl(adminDto.getPhotoUrl());
        }
        if(StringUtils.hasText(adminDb.getUsername())){
            adminDb.setUsername(adminDb.getUsername());
        }
        adminMapper.updateById(adminDb);
        return Result.success();
    }

    @Autowired
    private MinIOConfig minIOConfig;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public String fileUpload(MultipartFile multipartFile) {
        try {
            // 连接客户端
            MinioClient minioClient = minIOConfig.buildMinioClient();
            // 判断桶是否存在
            boolean isBucket = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            if (!isBucket) {
                // 不存在创建一个
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            } else {
                // 提示程序员存在
                System.out.println("Bucket 'test' already exists.");
            }

            // 设置存储路径
            // 当天作为目录
            String date = DateUtil.format(new Date(), "yyyyMMdd");
            // 唯一id作为图片路径
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 组合＋业务
            String fileName = "adminavatar" + "/" + date + "/" + uuid + multipartFile.getOriginalFilename();
            System.out.println(fileName);

            // 构建上传参数
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(fileName)
                    .build();
            // 上传
            minioClient.putObject(putObjectArgs);
            // 将路径返回
            return minIOConfigProperties.getReadPath() + "/" + minIOConfigProperties.getBucket() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return
     */
    public Admin onView() {
        Admin admin = new Admin();
        admin.setUsername("访客");
        admin.setToken("visitorviewingrightstoken");
        admin.setPhotoUrl("http://127.0.0.1:9000/blog/adminavatar/20240703/c1105a00eacd48dea483bb16b9efc363H.png");
        stringRedisTemplate.opsForValue().set("visitor","visitorviewingrightstoken",30,TimeUnit.MINUTES);
        return admin;
    }

}
